package cn.zdxiang.base.http

import android.util.Log
import cn.zdxiang.base.BaseApp.Companion.getContext
import com.blankj.utilcode.util.AppUtils
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 *  Retrofit工厂类
 * @author jm
 * @date 2020-07-16
 */
object RetrofitFactory {

    /**
     * 默认20秒超时时间
     */
    private const val TIMEOUT = 1000 * 20L

    //缓存100Mb
    private val okHttpClientBuilder: OkHttpClient.Builder
        get() {
            return OkHttpClient.Builder()
                .readTimeout(
                    TIMEOUT,
                    TimeUnit.MILLISECONDS
                )
                .connectTimeout(
                    TIMEOUT,
                    TimeUnit.MILLISECONDS
                )
                .addInterceptor(buildHttpLoggingInterceptor())
                .cookieJar(getCookie())
                .cache(getCache())
        }

    fun factory(): Retrofit {
        val okHttpClient = okHttpClientBuilder.build()
        return Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("")
            .build()
    }

    private fun buildHttpLoggingInterceptor(): Interceptor {
        return HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
            if (AppUtils.isAppDebug()) {
                showLog("Okhttp", message)
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY)
    }

    private fun showLog(tag: String?, msg: String?) {
        var targetMsg = msg
        if (tag == null || tag.isEmpty() || targetMsg == null || targetMsg.isEmpty()) return
        val segmentSize = 3 * 1024
        val length = targetMsg.length.toLong()
        if (length <= segmentSize) { // 长度小于等于限制直接打印
            Log.w(tag, targetMsg)
        } else {
            while (targetMsg!!.length > segmentSize) { // 循环分段打印日志
                val logContent = targetMsg.substring(0, segmentSize)
                targetMsg = targetMsg.replace(logContent, "")
                Log.w(tag, logContent)
            }
            Log.w(tag, targetMsg) // 打印剩余日志
        }
    }

    /**
     * 获取cookie持久化
     */
    private fun getCookie(): ClearableCookieJar {
        return PersistentCookieJar(
            SetCookieCache(),
            SharedPrefsCookiePersistor(getContext())
        )
    }

    /**
     * 获取缓存方式
     */
    private fun getCache(): Cache {
        //缓存100Mb
        return Cache(
            File(getContext().cacheDir, "cache")
            , 1024 * 1024 * 100
        )
    }
}